package com.thoughtworks;


import java.util.ArrayList;
import java.util.HashMap;

public class Library {
    private final ArrayList<Rental> rentable;

    public String checkRespectiveUser =null;
    private final ArrayList<Rental> checkOutArray;
    private final HashMap<Rental, String> userCheckoutMapping;

    public Library(ArrayList<Rental> rentable){
        checkOutArray = new ArrayList<Rental>();
        userCheckoutMapping = new HashMap<Rental, String>();
        this.rentable = rentable;
    }

    public boolean checkOutItem(String libraryNumber, String name) {

        Rental deleteBook=new Books();
        boolean flag = false;
        for (Rental nameOfBook : rentable) {
            if (nameOfBook.getName().equals(name)) {
                flag = true;
                userCheckoutMapping.put(nameOfBook, libraryNumber);
                checkOutArray.add(nameOfBook);
                deleteBook = nameOfBook;

            }}
            rentable.remove(deleteBook);

            return flag;

    }

    public boolean returnItem(String libraryNumber, String name) {
        Rental addBook=null;
        boolean flag = false;
        for(Rental nameOfBook : checkOutArray)
        if(nameOfBook.getName().equals(name))
        {
            checkRespectiveUser = userCheckoutMapping.get(nameOfBook);
            if(checkRespectiveUser.equals(libraryNumber))
        {
            addBook=nameOfBook;
            rentable.add(addBook);
            flag=true;
        }}
            checkOutArray.remove(addBook);
            userCheckoutMapping.remove(addBook);
            return flag;
    }

    void displayCheckoutInformation() {
        String libraryNo=null;
        String checkedOutItem=null;
        for(Rental name : userCheckoutMapping.keySet())
        {
            checkedOutItem=name.getName();
            libraryNo= userCheckoutMapping.get(name);
            System.out.println(checkedOutItem + " is checked out by " + libraryNo);
        }
    }

    void displayCatalog(LibraryManager libraryManager) {
        System.out.format("%-50s%-50s%-50s%-50s\n\n", "Item", "Author/Director ", "Year", "Rating");
        for (Rental name : rentable)
            libraryManager.displayItem(name);
    }
}

